<template>
  <div class="personal-container">
    <!-- 个人信息卡片 -->
    <div class="profile-card">
      <div class="card-header" @click="toggleProfile">
        <el-icon class="header-icon">
          <UserFilled/>
        </el-icon>
        <h2 class="profile-title">修改个人资料</h2>
        <el-icon class="collapse-icon" :class="{ 'rotate-180': isProfileExpanded }">
          <ArrowDown/>
        </el-icon>
      </div>
      <el-collapse-transition>
        <div v-show="isProfileExpanded" class="card-content">
          <el-form class="form-section" :model="data.user" label-width="100px">
            <el-form-item label="用户名">
              <el-input v-model="data.user.username" disabled/>
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="data.user.email" placeholder="请输入邮箱"/>
            </el-form-item>

            <el-form-item label="电话" prop="phone">
              <el-input v-model="data.user.phone" placeholder="请输入手机号码"/>
            </el-form-item>

            <el-form-item label="存储空间" prop="storageQuota">
              <el-input :value="formatStorageQuota(data.user.storageQuota)" disabled=""/>
            </el-form-item>

            <el-form-item label="真实姓名">
              <el-input v-model="data.user.realName"/>
            </el-form-item>

            <el-form-item label="头像">
              <div class="avatar-uploader">
                <el-upload
                    :show-file-list="false"
                    :before-upload="beforeAvatarUpload"
                    :on-success="handleAvatarUpload"
                    class="avatar-upload"
                    :action="uploadUrl"
                >
                  <img v-if="data.user.avatar" :src="data.user.avatar" class="avatar"/>
                  <el-icon v-else class="avatar-uploader-icon">
                    <Plus/>
                  </el-icon>
                  <div class="avatar-hover">
                    <el-icon>
                      <Camera/>
                    </el-icon>
                    <span>点击上传</span>
                  </div>
                </el-upload>
                <div class="avatar-tips">支持 JPG/PNG 格式，大小不超过2MB</div>
              </div>
            </el-form-item>

            <div class="form-actions">
              <el-button
                  type="primary"
                  @click="handleInfoUpdate"
                  class="save-button"
              >
                保存修改
              </el-button>
            </div>
          </el-form>
        </div>
      </el-collapse-transition>
    </div>

    <!-- 修改密码卡片 -->
    <div class="profile-card">
      <div class="card-header" @click="togglePassword">
        <el-icon class="header-icon">
          <Lock/>
        </el-icon>
        <h2 class="profile-title">修改密码</h2>
        <el-icon class="collapse-icon" :class="{ 'rotate-180': isPasswordExpanded }">
          <ArrowDown/>
        </el-icon>
      </div>
      <el-collapse-transition>
        <div v-show="isPasswordExpanded" class="card-content">
          <el-form class="form-section" label-width="100px">
            <el-form-item label="当前密码">
              <el-input
                  v-model="passwordData.password"
                  type="password"
                  show-password
              />
            </el-form-item>

            <el-form-item label="新密码">
              <el-input
                  v-model="passwordData.newPassword"
                  type="password"
                  show-password
              />
            </el-form-item>

            <el-form-item label="确认密码">
              <el-input
                  v-model="passwordData.confirmPassword"
                  type="password"
                  show-password
              />
            </el-form-item>

            <div class="form-actions">
              <el-button
                  type="primary"
                  @click="handlePasswordUpdate"
                  class="save-button"
              >
                修改密码
              </el-button>
            </div>
          </el-form>
        </div>
      </el-collapse-transition>
    </div>
  </div>
</template>

<script setup>
import {reactive, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {updateInfoApi, updatePasswordApi} from '@/utils/API/auth/Index'
import {getLocalStroage, removeLocalStroage} from "@/utils/LocalStroageUtil";
import router from "@/router";

// 展开状态
const isProfileExpanded = ref(true)
const isPasswordExpanded = ref(false)

// 用户数据
const data = reactive({
  user: getLocalStroage() || {
    username: '',
    email: '',
    phone: '',
    storageQuota: 1024,
    avatar: '',
    realName: ''
  }
})

// 密码数据
const passwordData = reactive({
  password: '',
  newPassword: '',
  confirmPassword: '',
})

// 切换展开状态
const toggleProfile = () => {
  isProfileExpanded.value = !isProfileExpanded.value
  if (isProfileExpanded.value) isPasswordExpanded.value = false
}

const togglePassword = () => {
  isPasswordExpanded.value = !isPasswordExpanded.value
  if (isPasswordExpanded.value) isProfileExpanded.value = false
}

// 上传文件URL
const uploadUrl = import.meta.env.VITE_BASE_URL + "/files/upload"

// 头像上传处理
const beforeAvatarUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传JPG/PNG格式的图片!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!')
    return false
  }
  return true
}

const handleAvatarUpload = (res) => {
  if (res.code === 200) {
    data.user.avatar = res.data
    ElMessage.success('头像上传成功')
  }
}

// 更新个人信息
const handleInfoUpdate = async () => {
  try {
    const response = await updateInfoApi({
      username: data.user.username,
      email: data.user.email,
      phone: data.user.phone,
      storageQuota: data.user.storageQuota,
      usedStorage: data.user.usedStorage,
      avatar: data.user.avatar,
      realName: data.user.realName
    })

    if (response && response.code === 200) {
      ElMessage.success('个人信息更新成功')
      localStorage.setItem('system-user', JSON.stringify(data.user))
      // 0.5秒后刷新页面
      setTimeout(() => {
        window.location.reload()
      }, 500)
    } else {
      ElMessage.error(response?.msg || '更新失败')
    }
  } catch (error) {
    ElMessage.error('更新失败，请检查网络连接')
  }
}

// 修改密码
const handlePasswordUpdate = async () => {
  if (passwordData.newPassword !== passwordData.confirmPassword) {
    return ElMessage.error('两次输入的密码不一致')
  }

  try {
    const response = await updatePasswordApi({
      username: data.user.username,
      password: passwordData.password,
      newPassword: passwordData.newPassword,
      confirmPassword: passwordData.confirmPassword
    })

    if (response && response.code === 200) {
      ElMessage.success('密码修改成功')
      // 清空密码表单
      passwordData.password = ''
      passwordData.newPassword = ''
      passwordData.confirmPassword = ''
      removeLocalStroage();
      await router.push('/login')
    } else {
      ElMessage.error(response?.msg || '密码修改失败')
    }
  } catch (error) {
    ElMessage.error('密码修改失败，请检查网络连接')
  }
}

// 格式化存储配额
const formatStorageQuota = (quota) => {
  return `${quota / 1024 / 1024 /1024}G`
}

</script>

<style scoped>
.personal-container {
  max-width: 800px;
  margin: 24px auto;
  padding: 0 20px;
}

.profile-card {
  background: linear-gradient(145deg, #f5f5f7, #ffffff);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
  transition: all 0.3s ease;
}

.card-header {
  display: flex;
  align-items: center;
  padding: 16px 24px;
  cursor: pointer;
  transition: background 0.3s;
}

.card-header:hover {
  background: rgba(0, 0, 0, 0.02);
}

.header-icon {
  font-size: 24px;
  color: #c8161d;
  margin-right: 12px;
}

.profile-title {
  font-size: 18px;
  color: #333;
  margin: 0;
  flex: 1;
}

.collapse-icon {
  transition: transform 0.3s;
}

.rotate-180 {
  transform: rotate(180deg);
}

.card-content {
  padding: 24px;
  border-top: 1px solid #eee;
}

.form-section {
  max-width: 600px;
  margin: 0 auto;
}

.avatar-uploader {
  text-align: center;
}

.avatar-upload {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background: #f5f7fa;
  position: relative;
  margin: 0 auto;
  overflow: hidden;
  border: 2px dashed #dcdfe6;
  cursor: pointer;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  margin-top: 44px;
}

.avatar-hover {
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-upload:hover .avatar-hover {
  opacity: 1;
}

.avatar-tips {
  color: #999;
  font-size: 12px;
  margin-top: 8px;
}

.form-actions {
  text-align: center;
  margin-top: 32px;
}

.save-button {
  background: linear-gradient(90deg, #c8161d, #e54b4b);
  border: none;
  padding: 10px 32px;
  border-radius: 8px;
  color: white;
  transition: all 0.3s;
}

.save-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(200, 22, 29, 0.3);
}

.full-width {
  width: 100%;
}
</style>